using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using BoOnce.Components;
using BoOnce.GameLogic.Entities;
using Microsoft.Xna.Framework.Graphics;
using System.Collections;
using BoOnce.Helpers;

namespace BoOnce.Components
{
    class DrawableEntityComponent : DrawableGameComponent
    {

        private const int TABLE_SIZE = 3000;

        private List<DrawableEntity>[] _Entities;

        private SpriteBatch _SpriteBatch;

        public DrawableEntityComponent(Game game) : base(game) 
        {
            _Entities = new List<DrawableEntity>[TABLE_SIZE];
            for (int i = 0; i < TABLE_SIZE; i++)
            {
                _Entities[i] = new List<DrawableEntity>();
            }
            _SpriteBatch = new SpriteBatch(Game.GraphicsDevice);
        }

        public override void Initialize()
        {
            Logger.WriteInfo("DrawableEntityComponent[#" + this.UpdateOrder + "] init");
        }

        public void Add(DrawableEntity entity)
        {
            Add(entity, entity.DrawedOrder);
        }

        private void Add(DrawableEntity entity, int rank)
        {
            if (rank >= 0 && rank < TABLE_SIZE)
            {
                _Entities[rank].Add(entity);
                entity.DrawedOrder = rank;
            }
            else
            {
                Logger.WriteError(this,"rank outofbound:" + rank);
            }
        }

        public override void Draw(GameTime gameTime)
        {
            _SpriteBatch.Begin();
            for(int i=0; i < TABLE_SIZE; i++)
            {
                int entityCount = _Entities[i].Count;
                if (entityCount > 0)
                {
                    foreach (DrawableEntity entity in _Entities[i])
                    {
                        entity.QuickDraw(gameTime, _SpriteBatch);
                    }
                }
            }
            _SpriteBatch.End();
            Clear();
        }

        public override void Update(GameTime gameTime)
        {
            for (int i = 0; i < TABLE_SIZE; i++)
            {
                int entityCount = _Entities[i].Count;
                if (entityCount > 0)
                {
                    for (int j=0; j < entityCount; j++ )
                    {
                        _Entities[i][j].Update(gameTime);
                    }
                }
            }
        }

        public void Clear()
        {
            for (int i = 0; i < TABLE_SIZE; i++)
            {
                _Entities[i].Clear();
            }
        }

        public static int AutoDrawOrder(Vector2 position, float height) 
        {
            return (int)(position.Y - height) * 3;
        }
    }
}
